package com.springboot.shiro.controller;

import com.springboot.shiro.pojo.User;
import com.springboot.shiro.realm.CustomRealm;
import com.springboot.shiro.service.RoleService;
import com.springboot.shiro.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

/**
 * @Date: 2019/10/22 17:12
 * @author: ybzhu
 * @Description： 登录控制器
 */
@RestController
@RequestMapping("userInfo")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    /**
     * 创建固定写死的用户
     * @return
     */
    @RequiresPermissions("userInfo:add")
    @RequestMapping(value = "/add",method = RequestMethod.GET)
    @ResponseBody
    public String login() {

        User user = new User();
        user.setName("朱亚彬");
        Random random=new Random(10);
        user.setIdCardNum("410222222222222222"+random.toString());
        user.setUsername("ybzhu222"+random.toString());


        userService.insert(user);

        return "创建用户成功";

    }

    /**
     * 删除固定写死的用户
     * @return
     */
    @RequiresPermissions("userInfo:del")
    @RequestMapping(value = "/del",method = RequestMethod.GET)
    @ResponseBody
    public String del() {

        userService.del("ybzhu");

        return "删除用户名为ybzhu用户成功";

    }

    /**
     * 用户列表页
     * @return
     */
    @RequiresPermissions("userInfo:add")
    @RequestMapping(value = "/view",method = RequestMethod.GET)
    @ResponseBody
    public String view() {

        return "这是用户列表页";

    }


    /**
     * 给admin用户添加 userInfo:del 权限
     * @return
     */
    @RequestMapping(value = "/addPermission",method = RequestMethod.GET)
    @ResponseBody
    public String addPermission() {

        //在sys_role_permission 表中  将 删除的权限 关联到admin用户所在的角色
        roleService.addPermission(1,3);

        //添加成功之后 清除缓存
        DefaultWebSecurityManager securityManager = (DefaultWebSecurityManager) SecurityUtils.getSecurityManager();
        CustomRealm customRealm = (CustomRealm) securityManager.getRealms().iterator().next();
        //清除权限 相关的缓存
        customRealm.clearAllCache();
        return "给admin用户添加 userInfo:del 权限成功";

    }

    /**
     * 删除admin用户 userInfo:del 权限
     * @return
     */
    @RequestMapping(value = "/delPermission",method = RequestMethod.GET)
    @ResponseBody
    public String delPermission() {

        roleService.delPermission(1,3);
        //清理缓存
        CustomRealm.clearCache();
        return "删除admin用户userInfo:del 权限成功";
    }


}
